package com.lqd.mall.system.service.impl;

import com.lqd.mall.basis.constant.Constants;
import com.lqd.mall.basis.constant.UserConstants;
import com.lqd.mall.basis.exception.ExceptionCast;
import com.lqd.mall.basis.utils.StringUtils;
import com.lqd.mall.interaction.system.SysMenuEntity;
import com.lqd.mall.interaction.system.SysUserEntity;
import com.lqd.mall.interaction.system.qo.MenuQueryQo;
import com.lqd.mall.interaction.system.vo.MenuVo;
import com.lqd.mall.interaction.system.vo.MetaVo;
import com.lqd.mall.interaction.system.vo.RouterVo;
import com.lqd.mall.system.repository.SysMenuRepository;
import com.lqd.mall.system.service.ISysMenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 零起点
 * @create 2022-02-20 15:35
 */
@Service
public class SysMenuServiceImpl implements ISysMenuService {

    @Resource
    private SysMenuRepository sysMenuRepository;

    @Autowired
    EntityManager entityManager;

    @Override
    public List selectMenuList(Long userId, MenuQueryQo menuQueryQo) {
        if (userId == null || userId < 1) {
            ExceptionCast.cast("用户还没有登录!请登录");
        }
        StringBuilder sql = new StringBuilder();
        if (SysUserEntity.isAdmin(userId)) {
            sql.append("select  menu_id, menu_name, parent_id, order_num, path, component, `query`, is_frame, is_cache," +
                    " menu_type, visible, status, ifnull(perms,'') as perms, icon, create_time ,creat_by,del_flag " +
                    ", upate_by ,remark,upate_time,create_by from sys_menu ");
            if (!StringUtils.isAllEmpty(menuQueryQo.getMenuName(), menuQueryQo.getMenuType(),menuQueryQo.getStatus())) {
                sql.append(" where 1=1");
                if (StringUtils.isNotEmpty(menuQueryQo.getMenuName())) {
                    sql.append(" AND menu_name like concat('%', '" + menuQueryQo.getMenuName() + "', '%')");
                }
                if (StringUtils.isNotEmpty(menuQueryQo.getMenuType())) {
                    sql.append(" AND menu_type = '" + menuQueryQo.getMenuType() + "'");
                }
                if (StringUtils.isNotEmpty(menuQueryQo.getStatus())) {
                    sql.append(" AND visible = '" + menuQueryQo.getStatus() + "'");
                }
            }
            return entityManager.createNativeQuery(sql.toString(), SysMenuEntity.class).getResultList();
        } else {
            // entityManager.createNativeQuery();
            sql.append("select distinct m.menu_id, m.parent_id, m.menu_name, m.path, m.component, m.`query`, m.visible," +
                    " m.status, ifnull(m.perms,'') as perms, m.is_frame, m.is_cache, m.menu_type, m.icon, m.order_num, " +
                    "m.create_time ,m.creat_by,m.del_flag,m.upate_by,m.remark,m.upate_time ,m.create_by " +
                    "from sys_menu m left join sys_role_menu rm on m.menu_id = rm.menu_id" +
                    " left join sys_user_role ur on rm.role_id = ur.role_id" +
                    " left join sys_role ro on ur.role_id = ro.role_id");
            sql.append(" where ur.user_id = '"+userId+"'");
            if (!StringUtils.isAllEmpty(menuQueryQo.getMenuName(), menuQueryQo.getMenuType(),menuQueryQo.getStatus())) {

                if (StringUtils.isNotEmpty(menuQueryQo.getMenuName())) {
                    sql.append(" AND menu_name like concat('%', '" + menuQueryQo.getMenuName() + "', '%')");
                }
                if (StringUtils.isNotEmpty(menuQueryQo.getMenuType())) {
                    sql.append(" AND menu_type = '" + menuQueryQo.getMenuType() + "'");
                }
                if (StringUtils.isNotEmpty(menuQueryQo.getStatus())) {
                    sql.append(" AND visible = '" + menuQueryQo.getStatus() + "'");
                }

            }
        }


        return entityManager.createNativeQuery(sql.toString(), SysMenuEntity.class).getResultList();
    }

    @Override
    public SysMenuEntity findMenuById(Integer menuId) {
        return sysMenuRepository.findById((long) menuId).orElse(null);
    }


    @Override
    public List<String> getMenuPermission(Long userId) {
        List<String> perms = new ArrayList<>();
        // 管理员拥有所有权限
        if (SysUserEntity.isAdmin(userId)) {
            perms.add("*:*:*");
        } else {
            Set<String> perms1 = sysMenuRepository.selectMenuPermsByUserId(userId);
            for (String perm : perms1) {
                if (StringUtils.isNotEmpty(perm)) {
                    perms.addAll(Arrays.asList(perm.trim().split(",")));
                }
            }
        }
        return perms;
    }

    @Override
    public List<MenuVo> selectMenuTreeByUserId(Long userId) {
        List<SysMenuEntity> menus;
        // 管理员拥有所有权限
        if (SysUserEntity.isAdmin(userId)) {
            menus = sysMenuRepository.findAll();
        } else {
            menus = sysMenuRepository.selectMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, 0);
    }

    @Override
    public List<RouterVo> buildMenus(List<MenuVo> menus) {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (MenuVo menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
            List<MenuVo> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/inner");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }


    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(MenuVo menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }


    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(MenuVo menu) {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(MenuVo menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(MenuVo menu) {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getPath());
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return
     */
    private String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[]{Constants.HTTP, Constants.HTTPS},
                new String[]{"", ""});
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(MenuVo menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(MenuVo menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    private List<MenuVo> getChildPerms(List<SysMenuEntity> menus, int parentId) {

        return menus.stream().filter(item -> item.getParentId() == parentId)
                .map(item -> {
                    MenuVo menuVo = new MenuVo();
                    BeanUtils.copyProperties(item, menuVo);
                    menuVo.setChildren(getChildPerms(menus, (int) item.getMenuId()));
                    return menuVo;
                }).collect(Collectors.toList());

    }


}
